package com.lbw.servlet;

import com.lbw.model.Worker;
import com.lbw.util.ProFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "WorkerServlet")
public class WorkerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String workerId = request.getParameter("worker-id");
        String job = request.getParameter("job");
        int age = Integer.parseInt(request.getParameter("age"));
        String filePath = "/Users/lbw/Desktop/test.properties";
        File file = new File(filePath);
        if (!file.exists()) { // 如果当前配置文件不存在, 创建文件
            file.createNewFile();
        }
        String item = ProFile.GetValueByKey(filePath, "index");
        int index = 1;
        if (item != null) {
            index = Integer.parseInt(item);
        }
        ProFile.WriteProperties(filePath, "worker" + index, index + "," + name + "," + workerId + "," + job + "," + age);
        index++;
        ProFile.WriteProperties(filePath, "index", index + "");

        //4. ArrayList操作
        List<String> strs = null;
        List<Worker> workers = new ArrayList<>();
        try {
            strs = ProFile.GetAllValues(filePath);
            System.out.println(strs);
            Worker worker = null;
            for (String str : strs) {
                String[] s = str.split(",");
                if (s.length == 5) {
                    index = Integer.parseInt(s[0]);
                    name = s[1];
                    workerId = s[2];
                    job = s[3];
                    age = Integer.parseInt(s[4]);
                    worker = new Worker(index, name, workerId, job, age);
                    workers.add(worker);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //5. 存入request
        System.out.println(workers.size());
        request.setAttribute("workers", workers);

        //6. 转发
        request.getRequestDispatcher("ch3/show.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
